<template>
  <div id="wft-page-h5-preview" class="animate__animated">
    <div class="tool">
      <div class="item">
        <div class="label">设备类型</div>
        <el-select size="mini" v-model="config.type" @change="typeChange" class="wft-w-130">
          <el-option label="iphone" value="iphone" />
          <el-option label="ipad" value="ipad" />
          <el-option label="ipad-mini" value="ipad-mini" />
          <el-option label="browser" value="browser" />
        </el-select>
      </div>
      <div class="item">
        <div class="label">缩放</div>
        <el-input-number size="mini" v-model="config.scale" :min="1" :max="30" controls-position="right" class="wft-w-130" />
      </div>
      <div class="item">
        <div class="label">皮肤</div>
        <el-select size="mini" v-model="skins" @change="skinsChange" class="wft-w-130">
          <el-option label="浅色" value="#fff" />
          <el-option label="深色" value="black" />
        </el-select>
      </div>
      <el-button @click="$emit('close')" size="medium" circle icon="el-icon-close" class="wft-preview-close" />
    </div>
    <div class="container">
      <div v-if="showDeviceMock">
        <DeviceMocks v-bind="config">
          <div class="page-generate-h5-container-outer">
            <div class="page-generate-h5-container" :style="mobileContainerPanelPreviewStyle">
              <DynamicComp v-for="item in renderComps" :key="item.id" :comp="item" />
            </div>
          </div>
        </DeviceMocks>
      </div>
    </div>
  </div>
</template>
<script>
import DeviceMocks from '../lib/deviceMocks/vue-and-devices-mocks.umd.min.js'
import DynamicComp from './dynamicComp.vue';
import { getUuid } from '../utils'
import request from '../../../utils/request'
export default {
  data() {
    return {
      showDeviceMock: true,
      config: {
        type: 'iphone',
        scale: 22,
        width: null,
        height: null,
        skins: ['black', 'inverted', 'noShadow', 'touch']
      },
      skins: 'black',
      renderComps: []
    }
  },
  components: { DeviceMocks, DynamicComp },
  props: {
    panelJson: {
      type: Object,
      default: () => ({
        container: {
          title: '工作空间',
          width: 100,
          height: 100,
          backgroundColor: '#fff',
          backgroundImage: '',
          backgroundSize: '100% 100%',
          isConflictCheck: false
        },
        comps: []
      })
    }
  },
  computed: {
    mobileContainerPanelPreviewStyle() {
      const { width, height, backgroundColor, backgroundImage, backgroundSize } = this.panelJson.container
      return {
        width: width + '%',
        height: height + '%',
        backgroundColor: backgroundColor,
        backgroundImage: `url(${backgroundImage})`,
        backgroundSize: backgroundSize
      }
    },
    comps() {
      return this.panelJson.comps.filter(comp => comp.config.visible)
    }
  },
  mounted() {
    this.handlerComps()
  },
  methods: {
    // 渲染前的处理
    async handlerComps() {
      const comps = JSON.parse(JSON.stringify(this.comps))
      const basicContainers = comps.filter(comp => comp.compKey == 'seniorContainer')
      if(basicContainers && basicContainers.length > 0) {
        for(let i = 0; i < basicContainers.length; i++) {
          const { server } = basicContainers[i]
          if(server.dataType == '1' && server.config.url) {
            try {
              basicContainers[i].data = await this.getBasicContainerData(server)
            } catch(e) {
              console.error(e, 'basicContainers interface error')
            }
          }
          let bcCopy = null
          for(let j = 0; j < basicContainers[i].data.length; j++) {
            if(bcCopy) {
              bcCopy.id = getUuid()
              bcCopy.grid.top = bcCopy.grid.top + bcCopy.grid.height + 20
              console.log(this.getAttrs(bcCopy.attrs).gutter, "this.getAttrs(bcCopy.attrs).gutter")
              bcCopy.resizeGrid.top = this.percentageToNum(bcCopy.resizeGrid.top) + this.percentageToNum(bcCopy.resizeGrid.height) + this.getAttrs(bcCopy.attrs).gutter + '%'
              bcCopy.children.forEach(child => {
                child.id = getUuid()
                child.parentId = bcCopy.id
                child.data = JSON.parse(JSON.stringify(basicContainers[i].data[j][child.field]))
              })
              comps.push(JSON.parse(JSON.stringify(bcCopy)))
            } else {
              basicContainers[i].children.forEach(child => {
                child.data = JSON.parse(JSON.stringify(basicContainers[i].data[j][child.field]))
              })
              bcCopy = JSON.parse(JSON.stringify(basicContainers[i]))
            }
          }
        }
      }
      this.renderComps = comps
    },
    getAttrs(attrList) {
      const attrs = {}
      if(attrList && attrList.length) {
        for(let attr of attrList) {
          attrs[attr.name] = attr.value
        }
      }
      return attrs
    },
    percentageToNum(str) {
      return Number(str.replace('%', ''))
    },
    // 调用容器组件basicContainer接口
    getBasicContainerData(server) {
      return new Promise((resolve, reject) => {
        try {
          let url = server.config.url
          let method = server.config.method
          let headers = this.getOptions(server.config.headers)
          let params = this.getOptions(server.config.params)
          let data = this.getOptions(server.config.body)
          request({ url, method, headers, params, data }).then(res => {
            const func = new Function('res', server.handler)
            resolve(func.call(this, res))
          })
        } catch(e) {
          reject(e)
        }
      })
    },
    getOptions(data) {
      const target = {}
      data.forEach(item => {
        try {
          target[item.key] = JSON.parse(item.value)
          if(typeof target[item.key] !== 'object') {
            target[item.key] = String(target[item.key])
          }
        }catch(e) {
          target[item.key] = item.value
        }
      })
      return target
    },
    init() {
      this.config = {
        type: 'iphone',
        scale: 22,
        width: null,
        height: null,
        skins: ['black', 'inverted', 'noShadow', 'touch']
      }
      this.skins = 'black'
      const pageH5PreviewEl = document.getElementById('wft-page-h5-preview')
      pageH5PreviewEl.classList.add('animate__jackInTheBox')
      pageH5PreviewEl.classList.remove('animate__zoomOut')
    },
    close() {
      const pageH5PreviewEl = document.getElementById('wft-page-h5-preview')
      pageH5PreviewEl.classList.add('animate__zoomOut')
      pageH5PreviewEl.classList.remove('animate__jackInTheBox')
    },
    // 皮肤切换
    skinsChange() {
      this.config.skins = [this.skins, 'noShadow']
    },
    // 设备类型切换
    typeChange() {
      this.showDeviceMock = false
      const scales = {
        'iphone': 22,
        'ipad': 13,
        'ipad-mini': 13,
        'browser': 17
      }
      this.config.scale = scales[this.config.type]
      this.$nextTick(() => {
        this.showDeviceMock = true
      })
    }
  }
}
</script>
<style scoped>
#wft-page-h5-preview {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  background-color: #edf2fa;
}

#wft-page-h5-preview > .tool {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #e4e7ed;
  box-sizing: border-box;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

#wft-page-h5-preview > .tool > .item {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

#wft-page-h5-preview > .tool > .item > .label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

#wft-page-h5-preview > .container {
  width: 100%;
  height: calc(100% - 50px);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.wft-preview-close {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
}

.wft-w-130 {
  width: 130px;
}

.page-generate-h5-container-outer {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

.page-generate-h5-container {
  position: relative;
  overflow: hidden;
}

/* 整个滚动条 */
::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  box-sizing: border-box;
}

/* 滚动条有滑块的轨道部分 */
::-webkit-scrollbar-track-piece {
  border-radius: 5px;
}

/* 滚动条滑块(竖向:vertical 横向:horizontal) */
::-webkit-scrollbar-thumb {
  cursor: pointer;
  background-color: rgba(70, 70, 73, .1);
  border-radius: 5px;
}

/* 滚动条滑块hover */
::-webkit-scrollbar-thumb:hover {
  background-color: #c7c9cc;
}

/* 同时有垂直和水平滚动条时交汇的部分 */
::-webkit-scrollbar-corner {
  display: block;
  background-color: #f5f5f5;
}
</style>
